package services.user;

import org.apache.commons.lang3.StringUtils;

import services.exception.*;
import services.security.*;
import utils.*;

import dto.user.*;
import models.user.*;
import models.pubobj.*;

public class AniUserInfoService{

	//public user info generate service
	public static void publicUserRegister(LocalUserInfoDto oneLocalUserRegInfo){
		checkUserRegInfo(oneLocalUserRegInfo);
		saveUser(oneLocalUserRegInfo, getUserRoleWithKey(AniUserRole.RoleKeys.ANI_USER.name()));
	}
	//admin user register service
	public static void adminUserRegister(LocalUserInfoDto oneLocalUserRegInfo){
		checkUserRegInfo(oneLocalUserRegInfo);
		saveUser(oneLocalUserRegInfo, getUserRoleWithKey(AniUserRole.RoleKeys.ANI_ADMIN.name()));
	}
	
	//check user register info legality
	protected static void checkUserRegInfo(LocalUserInfoDto userRegInfo) {
		//need catch in controller
		checkRequiredUserRegisterInfo(userRegInfo);
		
		AniPatternUtils.checkEmailFormatLegality(userRegInfo.email);
		AniUserInfoService.checkScreenNameLegality(userRegInfo.screenName);
		
		checkUserEmailUnique(userRegInfo.email);
		checkUserScreenNameUnique(userRegInfo.screenName);
	}
	private static void checkRequiredUserRegisterInfo(LocalUserInfoDto localUserRegInfo){
		if(StringUtils.isEmpty(localUserRegInfo.email)){
			throw new AniAuthException("EMAIL_IS_REQUIRED");
		}
		if(StringUtils.isEmpty(localUserRegInfo.md5Pwd)){
			throw new AniAuthException("PWD_IS_REQUIRED");
		}
	}
	//check user unique
	private static void checkUserEmailUnique(String userEmail){
		AniUser curUser = AniUser.findByEmail(userEmail.trim());
		if(curUser != null){
			throw new AniAuthException("USER_EMAIL_EXISTS");
		}
	}
	//check user screenName unique
	private static void checkUserScreenNameUnique(String screenName){
		AniUser curUser = AniUser.findByScreenName(screenName);
		if(curUser != null){
			throw new AniAuthException("USER_SCREENNAME_EXISTS");
		}
	}
	//---check user screenname unique
	//-save user
	protected static void saveUser(LocalUserInfoDto oneLocalUserRegisterInfo, AniUserRole role){
		new AniUser(
				oneLocalUserRegisterInfo.email,
				oneLocalUserRegisterInfo.md5Pwd,
				AniSecurityService.getObjectStateWithKey(AniObjectState.States.ACTIVATED.name()),
				role,
				oneLocalUserRegisterInfo.screenName
				);
	}
	//--user role existence
	private static AniUserRole getUserRoleWithKey(String roleKey){
		AniUserRole oneUserRole = AniUserRole.findByRoleKey(roleKey);
		if(oneUserRole == null){
			throw new AniRuleException("USER_ROLE_FORMAT_ILLEGAL");
		}
		return oneUserRole;
	}
	
	//screenname legality
	public static void checkScreenNameLegality(String screenName){
		if(!AniPatternUtils.isMatches(screenName.trim(), AniPatternUtils.SCREENNAME_PATTERN)){
			throw new AniRuleException("SCREENNAME_FORMAT_ILLEGAL");
		}
	}
}	

